import {defineStore} from "pinia";
// 使用缓存对象
import StorageUtil from "@/utils/StorageUtil.ts";
import {tokenName, authoritiesName} from "@/config/globalConfig.ts";
// 登录Api
import {loginAPI, getInfoAPI, logoutAPI} from "@/api/user.ts";
import type {User} from "@/store/types/user";

// 用户状态管理
export const useUserStore = defineStore({
    id: 'user',
    state: (): User<{
        username: string,
        avatar: string
    }> => {
        return {
            // token
            token: StorageUtil.getDefault(tokenName),
            // 权限
            authorities: StorageUtil.getDefault(authoritiesName),
            info: null
        }
    },
    actions: {
        // 用户登录获取token
        async login(username: string, pwd: string) {
            return new Promise<void>((resolve, reject) => {
                loginAPI({
                    username,
                    pwd
                }).then(res => {
                    const data = res.data;
                    this.token = data.token;
                    StorageUtil.setDefault(tokenName, data.token);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        },
        // 利用token获取用户信息
        getInfo() {
            return new Promise<void>((resolve, reject) => {
                getInfoAPI().then(res => {
                    const data = res.data;
                    this.authorities = data.authorities;
                    this.info = {
                        username: data.username,
                        avatar: data.avatar
                    };
                    StorageUtil.setDefault(authoritiesName, data.authorities);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        },
        // 退出登录
        logout() {
            return new Promise<void>((resolve, reject) => {
                logoutAPI().then(() => {
                    // console.log(res.msg);
                    resolve();
                }).catch(err => {
                    console.log("错误")
                    console.log(err);
                    reject();
                })
            })
        },
        // 清空关于user相关的信息
        clearUserInfo() {
            StorageUtil.clearItemDefault(authoritiesName);
            StorageUtil.clearItemDefault(tokenName);
            this.info = null;
            this.token = null;
        }
    }
})